import axios from "axios";
import { useUserStore } from "../stores/userStore";

const http = axios.create({
  // cofig 中配置基础url
  baseURL: "https://blog.hope-api.top/api",
  // 配置超时时间
  timeout: 5000,
  headers: {
    "Content-Type": "application/json;charset=utf-8", // 设置请求头的编码为 UTF-8
    withCredentials: true
  },
});

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    //每次请求携带token
    const token = useUserStore().token
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (e) => Promise.reject(e)
);

// axios响应拦截器
http.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (e) => {
    if (e.response.status === 400) {
      ElNotification({
        title: 'Error',
        message: e.response.data.msg,
        type: 'error',
      })
    }
    return Promise.reject(e);
  }
);

export default http;
